"use client";

import { useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { UserPlus, Loader2, X } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import { del, post } from "@/lib/request";
import { get } from "@/lib/request";
import { SearchFriendListResponse } from "./type";

interface Friend {
  id: string;
  username: string;
  avatar: string | null;
  status?: string;
}

interface FriendRequest {
  requestId: string;
  from: {
    id: string;
    username: string;
    avatar: string | null;
  };
}

export interface FriendListProps {
  onFriendSelect: (friend: Friend) => void;
  selectedFriend: Friend | null;
}

export default function FriendList({
  onFriendSelect,
  selectedFriend,
}: FriendListProps) {
  const [friends, setFriends] = useState<Friend[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [requests, setRequests] = useState<FriendRequest[]>([]);
  const [reqLoading, setReqLoading] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [searchResult, setSearchResult] = useState<SearchFriendListResponse>(
    []
  );
  const [searching, setSearching] = useState(false);
  const [sending, setSending] = useState(false);

  useEffect(() => {
    Promise.all([
      fetchFriendList(),
      fetchRequests(), // 首次加载
    ]);

    // 设置每15秒轮询一次
    let intervalId;
    if (addDialogOpen) {
      intervalId = setInterval(fetchRequests, 15000);
    }
    if (intervalId) {
      // 组件卸载时清除定时器
      return () => clearInterval(intervalId);
    }
  }, []);

  const fetchFriendList = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await get("/friends/list");
      const data = res.data;
      if (data === null) {
        console.error("服务端错误", error);
        return;
      }
      setFriends(data);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchRequests = async () => {
    setReqLoading(true);
    try {
      const res = await get("/friends/requests");
      // 映射后端返回的数据以匹配前端接口
      const mappedRequests = (res.data || []).map((req: any) => ({
        requestId: req.requestId,
        from: req.sender,
      }));
      setRequests(mappedRequests);
    } catch {
      setRequests([]);
    } finally {
      setReqLoading(false);
    }
  };

  const handleAccept = async (id: string) => {
    try {
      await post("/friends/accept", { requestId: id });
      toast.success("已接受好友请求");
      fetchRequests();
      fetchFriendList();
    } catch {
      toast.error("操作失败");
    }
  };

  const handleReject = async (id: string) => {
    try {
      await post("/friends/reject", { requestId: id });
      toast.success("已拒绝好友请求");
      fetchRequests();
      fetchFriendList();
    } catch {
      toast.error("操作失败");
    }
  };

  const handleDeleteFriend = async (id: string) => {
    if (!window.confirm("确定要删除此好友吗? ")) return;
    try {
      const res = await del(`friends/${id}`);
      if (!res.data) {
        throw new Error("删除失败");
      }
      toast.success("已删除好友");
      fetchFriendList();
    } catch (error) {
      console.error(error);
    }
  };

  const handleSendRequest = async (userId: string) => {
    setSending(true);
    try {
      await post("/friends/add", { friendId: userId });
      toast.success("好友请求已发送");
      setAddDialogOpen(false);
      setSearchValue("");
      setSearchResult([]);
    } catch {
      toast.error("发送请求失败");
    } finally {
      setSending(false);
    }
  };

  const handleSearchUser = async (e: React.FormEvent) => {
    // 避免Electron刷新
    e.preventDefault();
    const trimValue = searchValue.trim();
    if (trimValue.length === 0) {
      return;
    }
    try {
      setSearching(loading);
      const res = await get("/friends/search", { q: trimValue });
      const data = res.data;
      if (!data) {
        return;
      }
      setSearchResult(data);
    } catch (error) {
      setSearchResult([]);
      console.log("搜索失败", error);
      toast.error("搜索失败，服务端错误");
    } finally {
      setSearching(false);
    }
  };

  return (
    <div className="h-full flex flex-col bg-white dark:bg-stone-900">
      {/* 新的朋友按钮 */}
      <div className="border-b bg-white dark:bg-stone-900">
        <button
          className="w-full flex items-center gap-2 px-4 py-3 hover:bg-gray-100 dark:hover:bg-stone-800 font-medium border-b border-gray-100 dark:border-stone-800 transition group"
          onClick={() => setAddDialogOpen(true)}
        >
          <UserPlus
            size={18}
            className="text-blue-500 group-hover:text-blue-600 transition"
          />
          <span className="ml-1">新的朋友</span>
        </button>
      </div>
      {/* 好友列表 */}
      <div className="flex-1 overflow-auto bg-white dark:bg-stone-900">
        {loading ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-400">
            <Loader2 className="animate-spin mb-2" /> 加载中...
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center h-full text-red-400">
            <X size={32} className="mb-2" /> {error}
          </div>
        ) : friends.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-400">
            <UserPlus size={32} className="mb-2" /> 暂无好友
          </div>
        ) : (
          <ul>
            {friends.map((f) => (
              <li
                key={f.id}
                className={`flex items-center px-4 py-3 border-b last:border-b-0 group cursor-pointer relative transition ${
                  selectedFriend && selectedFriend.id === f.id
                    ? "bg-blue-50 dark:bg-stone-700"
                    : "hover:bg-gray-50 dark:hover:bg-stone-800"
                }`}
                onClick={() => onFriendSelect(f)}
              >
                {/* 左侧高亮条 */}
                {selectedFriend && selectedFriend.id === f.id && (
                  <div className="absolute left-0 top-0 h-full w-1 bg-blue-500 rounded-r" />
                )}
                <Avatar className="h-9 w-9 z-10">
                  <AvatarImage src={f.avatar || undefined} alt={f.username} />
                  <AvatarFallback>
                    {f.username?.charAt(0).toUpperCase()}
                  </AvatarFallback>
                </Avatar>
                <div className="ml-3 flex-1 z-10">
                  <div className="font-medium text-base">{f.username}</div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
      {/* 新的朋友 Dialog */}
      <Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
        <DialogContent className="max-w-lg rounded-2xl shadow-2xl p-0 overflow-hidden">
          <DialogHeader className="p-6 pb-2 border-b">
            <DialogTitle>新的朋友</DialogTitle>
          </DialogHeader>
          <div className="p-6 pt-4">
            {/* 好友请求列表 */}
            <div className="mb-6">
              <div className="font-semibold mb-2">好友请求</div>
              {reqLoading ? (
                <div className="flex flex-col items-center text-gray-400 py-6">
                  <Loader2 className="animate-spin mb-2" /> 加载中...
                </div>
              ) : requests.length === 0 ? (
                <div className="flex flex-col items-center text-gray-400 py-6">
                  <UserPlus size={32} className="mb-2" /> 暂无好友请求
                </div>
              ) : (
                <ul>
                  {requests.map((req) => (
                    <li
                      key={req.requestId}
                      className="flex items-center justify-between py-2 border-b last:border-b-0"
                    >
                      <div className="flex items-center gap-2">
                        <Avatar className="h-8 w-8">
                          <AvatarImage
                            src={req.from.avatar || undefined}
                            alt={req.from.username}
                          />
                          <AvatarFallback>
                            {req.from.username?.charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <span className="font-medium">{req.from.username}</span>
                      </div>
                      <div className="flex gap-1">
                        <button
                          className="px-3 py-1 rounded bg-green-500 text-white text-xs hover:bg-green-600"
                          onClick={() => handleAccept(req.requestId)}
                        >
                          接受
                        </button>
                        <button
                          className="px-3 py-1 rounded bg-gray-300 text-xs hover:bg-gray-400"
                          onClick={() => handleReject(req.requestId)}
                        >
                          拒绝
                        </button>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
            {/* 添加好友表单 */}
            <form onSubmit={handleSearchUser} className="flex gap-2 mb-2">
              <input
                className="flex-1 border rounded px-3 py-2 text-sm focus:ring-2 focus:ring-blue-200 outline-none dark:bg-slate-200 dark:text-slate-900"
                placeholder="输入用户名搜索"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                disabled={searching}
                required
              />
              <button
                type="submit"
                className="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600 text-sm"
                disabled={searching || !searchValue.trim()}
              >
                搜索
              </button>
            </form>
            {searchResult &&
              searchResult.length > 0 &&
              searchResult.map((item, index) => {
                return (
                  <div className="border rounded p-2 flex items-center justify-between mt-2" key={index}>
                    <span>
                      用户名：{item.username}
                    </span>
                    <button
                      className="ml-2 px-3 py-1 rounded bg-green-500 text-white hover:bg-green-600"
                      onClick={() => handleSendRequest(item.id)}
                      disabled={sending}
                    >
                      {sending ? "发送中..." : "加好友"}
                    </button>
                  </div>
                );
              })}
            {searchResult === null && searchValue && !searching && (
              <div className="text-gray-400 text-sm mt-2 flex items-center gap-2">
                <X size={16} /> 未找到用戶
              </div>
            )}
          </div>
          <DialogFooter className="p-4 border-t">
            <button
              type="button"
              className="px-4 py-2 rounded bg-gray-100 hover:bg-gray-200 mt-2 dark:bg-slate-500 dark:hover:bg-gray-600"
              onClick={() => setAddDialogOpen(false)}
              disabled={sending}
            >
              关闭
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}